#pragma once
#include <iostream>
//Accept：
#include <sys/types.h>
#include <sys/socket.h>
//fcntl:
#include <unistd.h>
#include <fcntl.h>

#include <arpa/inet.h>
#include <netinet/in.h>

#include "Connection.hpp"
#include "TcpServer.hpp"

#include "HandlerConnection.hpp"

#include <cerrno>//errno

#include "Log.hpp"

#include <sys/epoll.h>



class Accept{
public:
    void SetNonBlock(int fd)//将指定的fd设置为非阻塞
    {
        int fl = fcntl(fd,F_GETFL);//获取fd的文件描述符
        if(fl < 0)
        {
            exit(0);
        }
        lg.LogMessage(Info,"set %d been non block\n",fd);
        fcntl(fd,F_SETFL,fl | O_NONBLOCK);//追加设置fd的文件描述符有O_NONBLOCK
    }
    Accept(){}
    ~Accept(){}


    void AcceptConnection(Connection* conn)
    {
        errno = 0;

        while(true)//使用循环的方法，防止ET模式下只进行一次的询问，而导致的连接丢失
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(conn->SockFD(),(struct sockaddr*)&peer,&len);
            if(sockfd > 0)//代表有链接
            {
                lg.LogMessage(Info,"get a new link sockfd is: %d\n",sockfd);
                SetNonBlock(sockfd);//设置该文件描述符 为 非阻塞的读取方式
                auto recver =  std::bind(&HandlerConnection::Recver,std::placeholders::_1);

                auto sender =  std::bind(&HandlerConnection::Sender,std::placeholders::_1);
                
                auto excepter =  std::bind(&HandlerConnection::Excepter,std::placeholders::_1);

                Connection* normal_conn = ConnectionFactory::BuildNormalConnection(sockfd,recver,sender,excepter,EPOLLIN | EPOLLET,conn->_R);

                normal_conn->_R->AddConnection(normal_conn);
            }
            else{//表示accept出错了，此时errno就会被设置，包头文件cerrno
                if(errno == EAGAIN)//该错误底层数据读完了，IO本质没错
                {
                    break;
                }
                else if(errno == EINTR)// 他是被信号给中断了，那么就继续
                {
                    continue;
                }
                else{
                    lg.LogMessage(Warning,"get a new link error\n");
                    break;
                }
            } 
        }  
    }


};